package com.sjf.day04.kmp;

/**
 * @author <huangtang>
 * @since 2022/1/18 11:03
 **/
public class ViolenceMatch {

    public static void main ( String[] args ) {
        String s1 = "'BBC ABCDAB ABCDABCDABDE";
        String s2 = "ABCDABD";
        int index = violenceMatch (s1 , s2);
        System.out.println (index);
    }

    /**
     * 暴力匹配算法
     *
     * @param s1 父字符串
     * @param s2 子字符串
     * @return 第一个匹配的字符串下标
     */
    public static int violenceMatch ( String s1 , String s2 ) {
        char[] c1 = s1.toCharArray ();
        char[] c2 = s2.toCharArray ();

        int l1 = s1.length ();
        int l2 = s2.length ();

        int i = 0;
        int j = 0;
        while (i < l1 && j < l2) { //防止匹配时越界
            if ( c1[i] == c2[j] ) {
                //匹配成功
                i++;
                j++;
            } else {
                i = i - (j - 1);
                j = 0;
            }
        }

        //判断是否匹配成功
        return j == l2 ? i - j : -1;
    }
}
